﻿using System;
using System.Web;
using Glimpse.Core;
using Glimpse.Core.Configuration;

namespace Glimpse.Elmah
{
    public class ClientHelper
    {
        public static HtmlString RenderIncludes()
        {
            if (!Module.Configuration.Enabled)
                return null;
            
            var context = HttpContext.Current;
            var contextWrapper = new HttpContextWrapper(context);
            if (GetGlimpseMode(contextWrapper) == GlimpseMode.Off)
                return null;

            var root = VirtualPathUtility.ToAbsolute("~/", context.Request.ApplicationPath);
            var script = string.Format("<script src=\"{0}glimpse.axd?r=Pager&resource=Pager\" type=\"text/javascript\"></script>", root);
            return new HtmlString(script);
        }

        private static GlimpseMode GetGlimpseMode(HttpContextBase contextBase)
        {
            var cookies = contextBase.Request.Cookies;
            var cookie = cookies[GlimpseConstants.CookieModeKey];
            if (cookie == null) 
                return GlimpseMode.Off;

            GlimpseMode mode;
            return !Enum.TryParse(cookie.Value, true, out mode) ? GlimpseMode.Off : mode;
        }
    }
}